package com.example.gobang.controller;

import com.example.gobang.constant.Constants;
import com.example.gobang.model.Result;
import com.example.gobang.model.UserInfo;
import com.example.gobang.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * 使用会话存储登录信息
     * @param userName
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result<UserInfo> login(String userName, String password, HttpServletRequest request) {
        log.info("login 获取到参数userName: {}, password: {}", userName, password);
        // 参数校验
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空!");
        }
        // 根据用户名，进行查询
        UserInfo userInfo = userService.selectByName(userName);
        // 判断用户是否存在
        if(userInfo == null) {
            Result.fail("用户名不存在!");
        }
        if(!password.equals(userInfo.getPassword())) {
            return Result.fail("用户名或密码错误!");
        }
        HttpSession session = request.getSession(true);
        session.setAttribute(Constants.USER, userInfo);
        return Result.success(userInfo);
    }

    /**
     * 注册
     * @param userName
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result<UserInfo> register (String userName, String password) {
        log.info("register 获取到参数userName: {}, password: {}", userName, password);
        // 参数校验
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空!");
        }
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserName(userName);
            userInfo.setPassword(password);
            int result = userService.insert(userInfo);
            if(result > 0) {
                return Result.success("注册成功!");
            }
            return Result.fail("注册失败!");
        }catch (org.springframework.dao.DuplicateKeyException e) {
            return Result.fail("用户名已存在");
        }
    }

    @GetMapping("/getUserInfo")
    @ResponseBody
    public Result<UserInfo> getUserInfo(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);
            UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USER);
            UserInfo newUser = userService.selectByName(userInfo.getUserName());
            return Result.success(newUser);
        }catch (NullPointerException e) {
            return Result.fail("用户未登录!");
        }
    }
}
